package zzzhc.image.recognize.filter;

import zzzhc.image.recognize.Filter;
import zzzhc.image.recognize.RecognizeContext;

public class MixFilter implements Filter {

	private static final long serialVersionUID = 3504961253393855733L;

	public void doFilter(RecognizeContext context) {
		int w = context.getWidth();
		int h = context.getHeight();
		RecognizeContext rc = new RecognizeContext((w - 2) / 2, (h - 2) / 2);
		for (int y = 1; y < h; y += 2) {
			for (int x = 1; x < w; x += 2) {
				int p = getValue(context, x, y);
				rc.setValue((x - 1) / 2, (y - 1) / 2, p);
			}
		}
		context.copy(rc);
		w = context.getWidth();
		h = context.getHeight();
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int p = context.getValue(x, y);
				if (p == 1) {
					int roundValue = context.getValue(x - 1, y)
							+ context.getValue(x + 1, y)
							+ context.getValue(x, y - 1)
							+ context.getValue(x, y + 1);
					if (roundValue == 0) {
						context.setValue(x, y, 0);
					}
				}
			}
		}
	}

	private int getValue(RecognizeContext context, int x, int y) {
		x = (x + 1) / 2 * 2 - 1;
		y = (y + 1) / 2 * 2 - 1;
		int v = context.getValue(x, y) + context.getValue(x + 1, y)
				+ context.getValue(x, y + 1) + context.getValue(x + 1, y + 1);
		return v > 2 ? 1 : 0;
	}

}
